#include "../../head/utils/antcpserver.h"
#include "../../head/utils/antcpsocket.h"
#include "../../head/utils/anthreadpool.h"
#include <QHostAddress>
#include <QString>
#include <QTextStream>
#include "../../head/mainwindow.h"
extern MainWindow *w;
anTcpServer::anTcpServer(QObject *parent, int maxConnections):QTcpServer(parent), maxConnections_(maxConnections)
{

}

anTcpServer::~anTcpServer()
{
    onClear();
}

void anTcpServer::setMaxPendingConnections(int numConnections)
{
    this->maxConnections_=numConnections;
    this->QTcpServer::setMaxPendingConnections(numConnections);
}

void anTcpServer::onClear()
{
    QString logdata;
    QTextStream log(&logdata);

    log<<"anTcpServer::onClear().";

    //增加连接 各个socket 的清理工作
    for(auto it = client_.begin(); it!= client_.end(); ++it){
         connect(this, &anTcpServer::endDisconnect, it.value(), &anTcpSocket::onEnd);
    }

    emit this->endDisconnect(-1);
    anThreadPool::instance().clear();
    client_.clear();

    qDebug().noquote()<<logdata;
}

void anTcpServer::onSockDisConnect(int handle, const QString &ip, quint16 port, QThread *th)
{
    QString logdata;
    QTextStream log(&logdata);

    log<<"anTcpServer::onSockDisConnect(handle="<<handle<<",ip="<<ip<<",port="<<port<<",th="<<th<<").";

    //得到目标socket
    anTcpSocket * disSocket = nullptr;
    disSocket = client_.value(handle);

    client_.remove(handle);//连接管理中移除断开连接的socket

    anThreadPool::instance().removeThread(th); //告诉线程管理类那个线程里的连接断开了

    qDebug().noquote()<<logdata;

    //通知目标 tcpsocket 做清理
    if (disSocket){
        connect(this, &anTcpServer::endDisconnect, disSocket, &anTcpSocket::onEnd);
    }

    emit endDisconnect(handle);
}

void anTcpServer::incomingConnection(qintptr handle)
{
    QString logdata;
    QTextStream log(&logdata);

    log<<"anTcpServer::incomingConnection("<<handle<<")";
    if (client_.size() > maxPendingConnections())//继承重写此函数后，QTcpServer默认的判断最大连接数失效，自己实现
       {
           QTcpSocket tcp;
           tcp.setSocketDescriptor(handle);
           tcp.disconnectFromHost();

           log<<"client num("<<client_.size()<<") > maxPendingConnections("<<maxPendingConnections()<<").";
           //qDebug().noquote()<<logdata;
            qDebug()<<logdata;
           return;
       }

       auto th = anThreadPool::instance().getThread();
       auto tcpTemp = new anTcpSocket(nullptr);
       tcpTemp->setSocketDescriptor(handle);
       tcpTemp->setSocketOption(QAbstractSocket::LowDelayOption, 1);
       tcpTemp->setSocketOption(QAbstractSocket::KeepAliveOption, 0);

       QString ip =  tcpTemp->peerAddress().toString();
       quint16 port = tcpTemp->peerPort();

       connect(tcpTemp,&anTcpSocket::sockDisConnect, this,&anTcpServer::onSockDisConnect);//NOTE:断开连接的处理，从列表移除，并释放断开的Tcpsocket，此槽必须实现，线程管理计数也是考的他
       connect(tcpTemp,&anTcpSocket::sendDataByNet,this,&anTcpServer::acceptSocketData);

       tcpTemp->moveToThread(th);
       client_.insert(handle, tcpTemp);
       log<<", th="<<th<<",tcp="<<tcpTemp<<", handle="<<handle<<",ip="<<ip<<",port="<<port<<",th="<<QThread::currentThread();

       emit connectClient(handle,ip,port);

       //qDebug().noquote()<<logdata;
       qDebug()<<logdata;
}

void anTcpServer::acceptSocketData(int handle,const QString & ip, quint16 prot, QThread *th,QString data){
    emit sendDataToMain(data);
}
